package 二叉树系列;

import java.util.*;

public class LevelOrder {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if(root==null) return ans;
        Deque<TreeNode> deque = new ArrayDeque<>();
        Deque<TreeNode> deque1 = new ArrayDeque<>();
        List<Integer> list = new ArrayList<>();
        deque.push(root);
        while (!deque.isEmpty()){
            TreeNode treeNode = deque.pop();
            if(treeNode.left!=null) deque1.push(treeNode.left);
            if(treeNode.right!=null) deque1.push(treeNode.right);
            list.add(treeNode.val);
            if(deque.isEmpty() ){
                ans.add(list);
                list = new ArrayList<>();
                while(!deque1.isEmpty()){
                    deque.push(deque1.poll());
                }
            }
        }
        return ans;
    }


    // 102.二叉树的层序遍历
    class Solution {
        public List<List<Integer>> resList = new ArrayList<List<Integer>>();

        public List<List<Integer>> levelOrder(TreeNode root) {
            checkFun01(root,0);
//            checkFun02(root);
            List<List<Integer>> ans = new ArrayList<List<Integer>>();
            for(int i=resList.size()-1;i>=0;i--){
                ans.add(resList.get(i));
            }
            return ans;
        }

        //DFS--递归方式
        public void checkFun01(TreeNode node, Integer deep) {
            if(node==null) return;
            deep++;

            if(resList.size()<deep){
                List<Integer> list = new ArrayList<>();
                resList.add(list);
            }

            resList.get(deep-1).add(node.val);

            checkFun01(node.left,deep);
            checkFun01(node.right,deep);
        }

        //BFS--迭代方式--借助队列
        public void checkFun02(TreeNode node) {
            if (node == null) return;
            Queue<TreeNode> que = new LinkedList<TreeNode>();
            que.offer(node);

            while (!que.isEmpty()) {
                List<Integer> itemList = new ArrayList<Integer>();
                int len = que.size();

                while (len > 0) {
                    TreeNode tmpNode = que.poll();
                    itemList.add(tmpNode.val);

                    if (tmpNode.left != null) que.offer(tmpNode.left);
                    if (tmpNode.right != null) que.offer(tmpNode.right);
                    len--;
                }

                resList.add(itemList);
            }

        }
    }
}
